<?php
namespace Frieza\Modules\Decorationtask\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\DecorationTask\TaskGroup;
use Doraemon\model\DecorationTask\BroadCast;


class BroadCastController extends Controller
{
    use BaseController;

    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }
    //任务列表
    public function index(Request $request,Content $content){

        $request = $request->all();
        $request = self::_filterWhere($request);
        return $content
            ->header('待办广播列表')
            ->breadcrumb(
                ['text' => '提示广播列表', 'url' => '/decorationtask/broadcast']
            )
            ->body(self::listAction($request));
    }

    public function listAction($request = []){

        $broadcast_infos = BroadCast::getBroadCastNormal();
        $gridModel = new pGridDataModel($broadcast_infos, count($broadcast_infos), [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1]
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->disableRowSelector();

            $grid->column('id')->sort();
            $grid->column('tag', '广播标签');
            $grid->column('content', '广播内容');
            $grid->column('content_color', '内容颜色')->display(function(){
                return '<p style="background-color: '.$this->content_color.';color:'.$this->content_color.';width: 50px; display: block">颜色</p>';
            });
            $grid->column('addtime', '展示时间')->display(function() {
                return '开始时间：'.$this->start_time." ~ ".'结束时间：'.$this->end_time;
            });
            $grid->column('edittime', '展示状态')->display(function() {
                if(strtotime($this->start_time) > time()) {
                    return '<p style="color:deeppink;">未开始</p>';
                } else if (strtotime($this->end_time) < time()) {
                    return '<p style="color:red;">已过期</p>';
                } else {
                    return '<p style="color:green;">展示中</p>';
                }
            });
            $grid->column('sort', '排序');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

        });

        $list = $listGrid->render();
        return $list;
    }

    //广播添加页面
    public function edit(Request $request,Content $content, $id = 0)
    {
        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('待办广播列表')
                ->breadcrumb(
                    ['text' => '待办广播管理', 'url' => '/decorationtask/broadcast'],
                    ['text' => '添加广播信息', 'url' => '/decorationtask/broadcast/create']
                )
                ->body(self::editAction($request, $id , True));
        } else {
            return $content
                ->header('待办广播列表')
                ->breadcrumb(
                    ['text' => '待办广播管理', 'url' => '/decorationtask/broadcast'],
                    ['text' => '修改广播信息', 'url' => '/decorationtask/broadcast/'.'/'.$id.'/edit']
                )
                ->body(self::editAction($request, $id, False));
        }

    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if(!$isCreate) {
            $data = BroadCast::getBroadCastById($id);
            if(isset($data['link_type']) && $data['link_type']) {
                $data['link'] = [
                    'link_type' => $data['link_type'],
                    'link_params' => (string)$data['link_params']
                ];
            }
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $form = new Form($data);
        }

        $form->text('tag', '广播标签')->setWidth(4, 2)->required('不能为空')->help('仅可输入一个词哦');
        $form->text('content', '广播内容')->required('不能为空');
        $form->color('content_color', '内容文字颜色')->default('#000000')->required('不能为空');
        $form->datetime('start_time', '广播开始展示时间')->default(date('Y-m-d H:i:s', time()))->required('必填');
        $form->datetime('end_time', '广播结束展示时间')->default(date('Y-m-d H:i:s', time()+86400))->required('必填');
        $form->linkSelect('link', '广播跳转链接');
        $form->number('sort', '广播排序')->setWidth(4, 2)->min(0)->default(0);

        $form->action('/admin/decorationtask/broadcast/save');
        return $form->render();
    }

    //添加、修改提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();

        if(isset($request['id'])) {
            $data = [
                'tag' => $request['tag'],
                'content' => $request['content'],
                'content_color' => $request['content_color'],
                'start_time' => $request['start_time'],
                'end_time' => $request['end_time'],
                'broadcast_status' => 1,
                'sort' => (int) $request['sort'],
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id,
            ];
            if($request['link_type']) {
                $data['link_type'] = (string) $request['link_type'];
                $data['link_params'] = (string) json_encode($request['link_params'], JSON_UNESCAPED_UNICODE);
            }

            $rs = BroadCast::edit($data, $request['id']);
            if($rs) {
                $success = new MessageBag([
                    'title' => '修改成功'
                ]);
                return redirect('/admin/decorationtask/broadcast')->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '修改失败'
                ]);
                return redirect('/admin/decorationtask/broadcast')->with(compact('error'));
            }
        } else {
            $data = [
                'tag' => $request['tag'],
                'content' => $request['content'],
                'content_color' => $request['content_color'],
                'start_time' => $request['start_time'],
                'end_time' => $request['end_time'],
                'broadcast_status' => 1,
                'sort' => (int) $request['sort'],
                'addtime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id
            ];
            if($request['link_type']) {
                $data['link_type'] = (string) $request['link_type'];
                $data['link_params'] = (string) json_encode($request['link_params'], JSON_UNESCAPED_UNICODE);
            }

            $rs = BroadCast::add($data);
            if($rs) {
                $success = new MessageBag([
                    'title' => '添加成功'
                ]);
                return redirect('/admin/decorationtask/broadcast')->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '添加失败'
                ]);
                return redirect('/admin/decorationtask/broadcast')->with(compact('error'));
            }
        }

    }

    //删除
    public function del($id = 0)
    {
        $broadCastInfo = BroadCast::getBroadCastById($id);
       if($broadCastInfo) {
           $data = [
               'broadcast_status' => BroadCast::STATUS_DELETE,
               'edittime' => date('Y-m-d H:i:s', time()),
               'admin_id' => Admin::user()->id
           ];

           $rs = BroadCast::edit($data, $id);
           if($rs) {
               return response()->json([
                   'status' => true,
                   'message' => "操作成功",
               ]);
           } else {
               return response()->json([
                   'status' => false,
                   'message' => "操作失败",
               ]);
           }
       }

    }

    //排序
    public function sort(Request $request)
    {
        $params = $request->all();
        $sort = $params['sort'];
        array_walk($sort, function(&$value, $key) {
            $value = ($value+1) * 10;
        });

        if($sort && is_array($sort)) {
            foreach($sort as $sort_key=>$sort_val) {
                $data = [
                    'sort' => $sort_val,
                    'admin_id' => Admin::user()->id,
                    'edittime' => date('Y-m-d H:i:s', time())
                ];
                $id = $sort_key;
                BroadCast::edit($data, $id);
            }
        }
        return response()->json([
            'message' => "操作成功"
        ]);
    }

}